<template>
  <div style="height: 100%">
    <el-tabs
      class="protect"
      v-model="protectKey"
      @tab-click="handleProtectTabChange"
    >
      <el-tab-pane
        v-for="protectItem in protectArr"
        :key="protectItem.key"
        :label="protectItem.name"
        :name="protectItem.key"
        style="height: 100%"
      >
        <div v-if="protectKey === 'form'" style="height: 100%">
          <div class="form-container">
            <div class="form-contain">
              <el-input
                v-model="searchKey"
                clearable
                placeholder="输入表单名称"
              />
              <div class="form-list">
                <el-menu
                  v-if="!checkMode"
                  style="--el-menu-active-color: var(--el-color-primary)"
                  :default-active="0"
                  @select="(index) => handleFormSelect(index)"
                >
                  <el-menu-item
                    v-for="(item, key) in searchResult"
                    :index="key"
                    :key="item.id"
                  >
                    {{ item.content.form.label }}
                  </el-menu-item>
                </el-menu>
                <div class="checkBox" v-else>
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                  >
                  <el-checkbox-group
                    v-model="checkList"
                    @change="handleCheckedCitiesChange"
                  >
                    <el-checkbox
                      v-for="(item, key) in searchResult"
                      :index="key"
                      :key="item.id"
                      :label="item.content.form.label"
                    />
                  </el-checkbox-group>
                </div>
              </div>
            </div>
            <div class="form-right">
              <div class="form-buttons">
                <el-button v-if="!checkMode" @click="beforeBatchActionHandler">
                  批量设置
                </el-button>
                <el-button
                  v-if="checkMode"
                  @click="
                    () => {
                      checkMode = false;
                      checkList = [];
                      cancelBatchActionHandler();
                    }
                  "
                >
                  取消批量设置
                </el-button>
                <el-button @click="saveAll" v-if="checkMode">
                  保存批量设置
                </el-button>
              </div>
              <el-form class="protect-form">
                <el-form-item
                  v-for="(val, key) in protectOpt"
                  :key="key"
                  :label="(protectItems[key] || key) + ':'"
                  label-width="200px"
                >
                  <el-radio-group
                    v-model="val.status"
                    @change="(status) => handleSaveOpt(status, val, key)"
                  >
                    <el-radio :label="3">保护</el-radio>
                    <el-radio
                      v-if="limitShow(key)"
                      @click="hanleShowTemp(val, val, key)"
                      :label="2"
                      style="width: 80px"
                      :disabled="val.limit == 3"
                      >部分保护</el-radio
                    >
                    <div class="el-radio" style="width: 80px" v-else></div>
                    <el-radio
                      :label="1"
                      :disabled="val.limit == 3 || val.limit === 2"
                      >不保护</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div
          v-else
          style="
            height: 100%;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
          "
        >
          <el-form class="protect-form" v-if="protectOpt.length">
            <el-form-item
              v-for="(opt, key) in protectOpt"
              :key="key"
              :label="opt.objectLabel"
              label-width="200px"
            >
              <el-radio-group
                v-if="opt.detail"
                v-model="opt.detail.status"
                @change="handleSaveOpt(null, null, key)"
              >
                <el-radio :label="3">保护</el-radio>
                <el-radio :disabled="opt.detail.limit == 3" :label="1"
                  >不保护</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-empty v-else></el-empty>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      width="500"
      :title="protectItems[template.key] + '部分保护设置'"
      :visible.sync="templateVisible"
    >
      <el-form
        class="protect-form"
        style="height: auto"
        v-if="template && template.templates && template.templates.length"
      >
        <el-form-item
          v-for="(item, key) in template.templates"
          :key="key"
          :label="item.label + ':'"
          label-width="200px"
        >
          <el-radio-group v-model="item.status" @change="handleTmpSaveOpt">
            <el-radio :label="3">保护</el-radio>
            <el-radio :label="1" :disabled="item.limit == 3 || item.limit === 2"
              >不保护</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-empty
        v-else
        :description="`当前表单未定义${protectItems[template.key]}`"
      ></el-empty>
    </el-dialog>
  </div>
</template>
<script>
const limitStatusArr = [
  "field",
  "rowformula",
  "checkformula",
  "sumformula",
  "referencefilter",
  "queryfilter",
  "apptreefilter",
  "customfilter",
];
const protectItem = {
  field: "字段",
  customquerytemplates: "自定义查询模板",
  customviewtemplates: "自定义查看模板",
  excelviewtemplates: "excel视图模板",
  charts: "图表",
  trigger: "回写公式",
  report: "报表公式",
  rowformula: "行间公式",
  checkformula: "校验公式",
  sumformula: "汇总行公式",
  referencefilter: "引用过滤公式",
  queryfilter: "查询过滤公式",
  apptreefilter: "导航树过滤公式",
  customfilter: "自定义查询过滤公式",
};

const deepClone = (source) => {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
};

export default {
  data() {
    return {
      protectItems: protectItem,
      protectKey: "form",
      currentProtectForm: null,
      protectOpt: [],
      protectFormList: [],
      templateVisible: false,
      template: {},
      searchKey: "",
      searchResult: [
        {
          content: {
            form: {
              label: "菜单",
            },
          },
        },
      ],
      checkAll: false,
      isIndeterminate: false,
      protectArr: [
        {
          name: "表单",
          key: "form",
        },
        {
          name: "导航树",
          key: "apptree",
        },
        {
          name: "门户",
          key: "portal",
        },
        {
          name: "网站",
          key: "website",
        },
        {
          name: "数据分析",
          key: "adhoc",
        },
        {
          name: "流程",
          key: "workflow",
        },
        {
          name: "微应用 ",
          key: "microapp",
        },
        {
          name: "问卷 ",
          key: "survey",
        },
      ],

      checkMode: false,
      checkList: [],
    };
  },

  computed: {
    spaceId() {
      return this.$store.state.spaceId;
    },
  },

  watch: {
    searchKey(val) {
      this.searchResult = this.protectFormList.filter((i) => {
        const label = i.content.form.label || "";
        return label.includes(val);
      });
    },
  },

  async mounted() {
    const spaceId = this.spaceId;
    const { data: res } = await this.$axios(
      `/magicflu/service/s/json/${spaceId}/forms/feed?start=0&limit=-1&bq=(workspaceId,eq,${spaceId})and(updated,orderby,desc)`
    );
    if (!res.feed || !res.feed.entry) return;
    const result = Array.isArray(res.feed.entry)
      ? res.feed.entry
      : [res.feed.entry];
    this.protectFormList = result;
    this.searchResult = result;
    const formId = result[0].id;
    const { data: _form } = await this.$axios.get(
      `/magicflu/service/s/${spaceId}/component/protectconfig?objectType=form&forApp=true&objectId=${formId}`
    );
    this.currentProtectForm = _form.entry[0];
    this.protectOpt = this.sortProtectOpt(_form.entry[0].detailSet);
  },

  methods: {
    limitShow(key) {
      if (this.checkMode && key !== "trigger" && key !== "report") return false;
      if (limitStatusArr.includes(key)) {
        return false;
      }
      return true;
    },

    /**
     * 批量设置，做个缓存
     */
    beforeBatchActionHandler() {
      this.checkMode = true;
      this.__backupProtectOpt = deepClone(this.protectOpt); // 备份
    },

    /**
     * 取消批量操作
     */
    cancelBatchActionHandler() {
      this.protectOpt = this.__backupProtectOpt;
      this.__backupProtectOpt = null;
    },

    async handleFormSelect(index) {
      console.log(index);
      const formId = this.searchResult[index].id;
      const spaceId = this.spaceId;
      const { data: res } = await this.$axios.get(
        `/magicflu/service/s/${spaceId}/component/protectconfig?objectType=form&forApp=true&objectId=${formId}`
      );
      if (res.entry.length) {
        console.log(res.entry[0]);
        this.currentProtectForm = res.entry[0];
        this.protectOpt = this.sortProtectOpt(res.entry[0].detailSet);
      }
    },

    async handleProtectTabChange(e) {
      const { name: key } = e;
      const spaceId = this.spaceId;

      if (key === "form") {
        const formId = this.protectFormList[0].id;
        const { entry = [] } = (
          await this.$axios.get(
            `/magicflu/service/s/${spaceId}/component/protectconfig?objectType=form&forApp=true&objectId=${formId}`
          )
        ).data;
        if (entry.length) {
          this.protectOpt = this.sortProtectOpt(entry[0].detailSet);
        }
      } else {
        const { entry = [] } = (
          await this.$axios.get(
            `/magicflu/service/s/${spaceId}/component/protectconfig?objectType=${key}&forApp=true`
          )
        ).data;
        if (entry.length) {
          const _entry = entry.map((i) => ({
            ...i,
            detail: JSON.parse(i.detailSet),
          }));
          this.protectOpt = _entry;
        } else {
          this.protectOpt = [];
        }
      }
    },

    handleCheckAllChange(val) {
      console.log(val);
      this.checkList = val
        ? this.searchResult.map((i) => i.content.form.label)
        : [];
      this.isIndeterminate = false;
    },

    handleCheckedCitiesChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.searchResult.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.searchResult.length;
    },

    hanleShowTemp(val, item = [], key) {
      if (val.limit === 3) return;
      if (this.protectKey === "form") {
        if (this.checkMode) return;
        if (key !== "trigger" && key !== "report") {
          console.log("template", item);
          this.template = item;
          this.template.key = key;
          this.templateVisible = true;
          return;
        }
      }
    },

    sortProtectOpt(detailSet) {
      const protectOptRes = {};
      const _protectOpt = JSON.parse(detailSet);
      for (const key in this.protectItems) {
        protectOptRes[key] = _protectOpt[key];
      }
      return protectOptRes;
    },

    // 保存
    async handleSaveOpt(status, item = [], key) {
      console.log(status, item, key);
      let params = {
        forApp: true,
      };
      const spaceId = this.spaceId;
      if (this.protectKey === "form") {
        if (this.checkMode) return;
        if (status === 2 && key !== "trigger" && key !== "report") {
          this.template = item;
          this.template.key = key;
          this.templateVisible = true;
          return;
        }
        params.objectType = this.currentProtectForm.objectType;
        params.objectId = this.currentProtectForm.objectId;
        params.detailSet = JSON.stringify(this.protectOpt);
        params.forApp = true;
        await this.$axios.post(
          `/magicflu/service/s/${spaceId}/component/protectconfig`,
          params
        );
      } else {
        const opt = this.protectOpt[key] || {};
        params = {
          objectId: opt.objectId,
          objectType: opt.objectType,
          detailSet: JSON.stringify(opt.detail),
          forApp: true,
        };
        await this.$axios.post(
          `/magicflu/service/s/${spaceId}/component/protectconfig`,
          params
        );
      }
      this.showTips("操作成功", "success");
    },

    showTips(msg, type) {
      this.$alert(msg, "提示", {
        confirmButtonText: "确定",
        showClose: true,
        closeOnClickModal: true,
        type: type || "success",
      });
    },

    async handleTmpSaveOpt() {
      const { key, templates } = this.template;
      const params = {
        objectType: this.currentProtectForm.objectType,
        objectId: this.currentProtectForm.objectId,
        forApp: true,
      };
      const _protectOpt = this.protectOpt;
      _protectOpt[key].status = 2;
      _protectOpt[key].templates = templates;
      params.detailSet = JSON.stringify(_protectOpt);
      // await API_Comps.saveOptSet(params);
      try {
        await this.$axios.post(
          `/magicflu/service/s/${this.spaceId}/component/protectconfig`,
          params
        );
        this.showTips("操作成功", "success");
      } catch (error) {
        this.showTips("操作失败", "error");
      }
    },

    saveAll() {
      if (!this.checkList.length) {
        // customAlert("至少勾选一个表单");
        this.showTips("至少勾选一个表单");
        return;
      }
      const formMap = {};
      const ids = [];
      this.protectFormList.forEach((i) => {
        formMap[i.content.form.label] = i.id;
      });
      for (const name of this.checkList) {
        ids.push(formMap[name]);
      }
      for (let i in this.protectOpt) {
        // ？
        this.protectOpt[i].templates ? (this.protectOpt[i].templates = []) : "";
      }
      let params = {
        objectType: "form",
        objectId: ids.join("#"),
        detailSet: JSON.stringify(this.protectOpt),
        forApp: true,
      };
      this.$axios
        .post(
          `/magicflu/service/s/${this.spaceId}/component/protectconfig`,
          params
        )
        .then(({ data: res }) => {
          if (res.errcode === "0") {
            // customAlert(res.errmsg);
            this.__backupProtectOpt = deepClone(this.protectOpt); // 备份
            this.showTips(res.errmsg);
            return;
          }
          this.checkList = [];
          this.protectOpt = [];
          // customAlert("保存成功");
          this.showTips("保存成功", "success");
          console.log("保存成功");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.protect {
  display: flex;
  flex-direction: column;
}

.checkBox {
  display: flex;
  flex-direction: column;

  .el-checkbox {
    box-sizing: border-box;
    padding: 10px 20px;
    height: 56px;
  }
}

.el-form {
  width: 600px;
}

.el-tabs {
  height: 100%;
}

.el-menu-item.is-active {
  color: var(--el-color-primary);
  background-color: #fafafc;
}

.form-right {
  display: flex;
  flex-direction: column;
}

.protect-form {
  box-sizing: border-box;
  margin-top: 20px;
  position: relative;
  padding: 30px;
  flex: 1;
  height: 0;
  background-color: #fafafc;
  overflow-y: auto;
}

.form-buttons {
  display: flex;
  justify-content: end;
  // margin-bottom: 20px;
}

.save-button {
  position: absolute;
  right: 20px;
  top: 10px;
}

.form-container {
  display: flex;
  height: 100%;

  .form-contain {
    margin-right: 30px;
    width: 250px;
    display: flex;
    flex-direction: column;
  }

  .form-list {
    border-radius: 4px;
    border: solid 1px #dddddd;
    margin-top: 20px;
    height: 0;
    flex: 1;
    overflow: auto;
  }
}

::-webkit-scrollbar {
  width: 10px;
  height: 16px;
  background-color: #f5f5f5;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  border-radius: 0px 5px 5px 0px;
  background: #dddddd;
}
</style>
